<template>
	<base-popup-small titleT="birthday.title">
		<div class="py-5">
			<base-tip textT="birthday.tip"></base-tip>
			<n-date-picker
				class="mt-7 mb-4"
				v-model:value="birthday"
				type="date"
				:is-date-disabled="birthdayInvalid"></n-date-picker>
			<base-text class="text-sm text-t-4" textT="profile.cannotChange" />
			<base-button
				class="mt-5"
				type="primary"
				:disabled="submitDisabled"
				:loading="loading"
				@click="onSubmit">
				{{ $t('action.confirm') }}
			</base-button>
		</div>
	</base-popup-small>
</template>

<script lang="ts" setup>
import { NDatePicker } from 'naive-ui'
import { BasePopupSmall, BaseTip, BaseText, BaseButton } from '@/components/base'
import { ref, computed } from 'vue'
import { useProfileStore } from '@/store'
import { setBirthday } from '@/api/profile'
import { useRequest } from '@/hooks'
import { fmtDate } from '@/utils'

const emits = defineEmits(['success'])

const profileStore = useProfileStore()

const birthday = ref(null)

const birthdayInvalid = (val: number) => {
	const now = new Date()
	const year = now.getFullYear()
	const month = now.getMonth()
	const date = now.getDate()
	const maxDate = new Date(year - 18, month, date)
	const minDate = new Date(year - 100, month, date)
	return val > maxDate.getTime() || val < minDate.getTime()
}

const submitDisabled = computed(() => birthday.value === null || birthdayInvalid(birthday.value))

const { run, loading } = useRequest(setBirthday, {
	showSuccess: true,
	showError: true,
	onSuccess: () => {
		profileStore.getUserInfo()
		emits('success')
	}
})

const onSubmit = () => {
	run({
		birthday: fmtDate(birthday.value!)
	})
}
</script>
